<template>
    <div class="cont">
        <nav-bar textColor="#333333" rightImg="https://h5.dhcc.wang/newprogram/wxRobot/nav_refresh_black.png" :title="title"
            bgStyle="#fff" :rotate.sync="reload" @leftClick="back" @rightClick="refresh" />
        <div class="cont-main p-12">
                <div class="flex user-info align-center">
                    <img v-lazy="config.avatar" class="avatar">
                    <div class="m-l-10 flex-sub flex flex-direction">
                       <div class="flex justify-between">
                        <span class="nickname color-white font-16">{{ config.nickname}}</span>
                        <div class="color-white font-12" @click="openPage">开通记录</div>
                       </div>
                        <span v-if="config.device_info && config.device_info.expires_time" class="font-12 color-9">到期时间：{{
                            config.device_info.expires_time |
                            formateTime }}</span>
                        <span v-else class="font-12 color-9">开通{{ title }}，自动分享轻松赚钱&gt;</span>
                    </div>

                
            </div>
            <!-- v-if="pageConfig" -->
            <template>
                <div class="custom-img flex justify-around align-center">
                   <div class="text-center" v-for="(item, index) in equityList" :key="index">
                        <img :src="item.icon">
                        <div class="font-13">{{item.name}}</div>
                   </div>
                </div>
                <template v-if="freeOptions.length > 0">
                    <div class="card-title">免费领取</div>
                    <div class="bg-white receive-free">
                        <div v-for="(item, index) in freeOptions" :key="index" @click="handleReceive(item)" class="item">
                            <img v-if="item.type == 'level'" class="icon"
                                src="https://h5.dhcc.wang/newprogram/wxRobot/icon_vip.png" alt="">
                            <img v-else class="icon" src="https://h5.dhcc.wang/newprogram/wxRobot/icon_commission.png"
                                alt="">
                            <div class="text">
                                <span class="van-multi-ellipsis--l2">{{ item.title }}</span>
                                <span class="text-sub">{{ item.sub_title }}</span>
                            </div>
                            <div class="flex align-center justify-center">
                                <span v-if="item.type == 'level'" :class="[item.status != 1 ? 'disabled' : '']"
                                    class="btn">{{ item.status == -1 ? `已领取` : `领取` }}</span>
                                <span v-else :class="[item.status != 1 ? 'disabled' : '', item.status == -1 ? 'month' : '']"
                                    class="btn">{{ item.status == -1 ? `本月已领` : `领取` }}</span>
                            </div>
                        </div>
                    </div>
                </template>
                <template v-if="config.mac_toll_rules && config.mac_toll_rules.length > 0">
                    <div class="card-title">付费开通</div>
                    <div class="m-t-10 m-b-10">
                        <van-swipe :loop="false" width="140" :show-indicators="false">
                            <van-swipe-item v-for="(item, index) in config.mac_toll_rules" :key="index"
                                @click="select(item)">
                                <div class="pay-list m-r-10 font-13 p-b-15"
                                    :class="payInfo.id == item.id ? 'pay-list-active' : 'color-0'">
                                    <div v-if="item.id==-1" class="new-tag tag font-10">新人首购</div>
                                    <div v-else-if="item.diy_price < item.origin_price" class="tag font-10">限时特惠</div>
                                    <div class="text-center">
                                        <div class="m-t-10">{{ item.months }}个月</div>
                                        <div class="m-t-5 text-bold">
                                            ￥<span class="font-24 numberFont">{{ item.diy_price }}</span>
                                        </div>
                                        <div class="price-original m-t-5 color-9">
                                            ￥{{ item.origin_price }}</div>
                                    </div>
                                </div>
                            </van-swipe-item>
                        </van-swipe>
                    </div>
                    <div @click="buy()" class="buy">确认并{{config.device_info && config.device_info.status?'续费':'开通'}}特权</div>
                    <!-- <div class="flex flex-direction price bg-white">
                        <template v-for="(item,index) in config.mac_toll_rules">
                            <div :key="index" class="price-item m-b-20 flex align-center justify-between">
                                <div :class="item.months == '1' ? 'active' : ''" class="price-item-l flex flex-direction">
                                    <span class="flex align-center">
                                        <i class="font-24 numberFont">￥{{item.final_price}}</i>
                                        <i v-if="item.months == '1'" class="m-l-5 tag font-10">限时特惠</i>
                                        <i v-else class="m-l-5 price-original">原价：￥{{item.origin_price}}</i>
                                    </span>
                                    <span class="m-t-5 font-11 color-9">
                                        <i v-if="item.months == '1'" class="active">
                                            月卡限时特惠<i v-if="calcDiscount(item.final_price,item.origin_price) > 0">{{calcDiscount(item.final_price,item.origin_price)}}折</i>，原价{{item.origin_price}}元/月
                                        </i>
                                        <i v-if="item.months == '3'">季卡 · {{(item.final_price / 3).toFixed(2)}}元/月</i>
                                        <i v-if="item.months == '6'">半年卡 · {{(item.final_price / 6).toFixed(2)}}元/月</i>
                                        <i v-if="item.months == '12'">年卡 · {{(item.final_price / 12).toFixed(2)}}元/月</i>
                                    </span>
                                </div>
                                <span @click="buy(item)" class="buy">购买</span>
                            </div>
                        </template>
                    </div> -->
                </template>
                <div class="notes bg-white p-20 radius10">
                    <h3 class="font-14">★ 开通须知（必读）</h3>
                    <p>1.需要通过您的微信号登录云端MAC协议才能正常使用。</p>
                    <p>2.由于微信规则的问题, 可能出现个别封号问题, 请知晓。</p>
                    <p>3.<b>一旦开通无法退款</b>，请谨慎开通。</p>
                    <p>4.部分功能可能会调整或者停止，无法对受此影响的用户退款，请谨慎开通。</p>
                    <p>5.确认支付后代表同意以上问题</p>
                </div>
            </template>
        </div>
        <!-- 支付方式 -->
        <van-popup v-model="showPay" position="bottom" close-on-popstate round closeable>
            <div class="payment p-20">
                <div class="font-18 text-center text-bold m-b-10">
                    选择支付方式
                </div>
                <div class="payment-title">
                    <span class="">{{config.device_info && config.device_info.status?'续费':'开通'}}{{ title }}，{{ payInfo.name }}</span>
                    <span class="">￥<i class="font-24 numberFont">{{ payInfo.diy_price }}</i></span>
                </div>
                <div class="payment-cont m-t-10">
                    <van-radio-group border v-model="checked" icon-size="18">
                        <van-cell-group>
                            <template v-for="(item, index) in paymentList">
                                <van-cell :key="index" clickable @click="checked = item.type">
                                    <template #title>
                                        <div class="radio-title flex align-center">
                                            <img class="icon" :src="item.icon" alt="">
                                            <span class="font-14">{{ item.name }}</span>
                                            <span v-if="item.type == 'credit'" class="wallet font-12">
                                                <i v-if="Number(wallet) > Number(payInfo.diy_price)">(￥{{ wallet }})</i>
                                                <i v-else>(余额不足)</i>
                                            </span>
                                        </div>
                                    </template>
                                    <template #right-icon>
                                        <van-radio :name="item.type" />
                                    </template>
                                </van-cell>
                            </template>
                        </van-cell-group>
                    </van-radio-group>
                </div>
                <div class="btn-group m-t-20 flex align-center justify-center">
                    <!-- <span @click="showPay = false" class="btn-group-item cancel">取消</span> -->
                    <span @click="submit" class="btn-group-item confrim">确认并支付 {{ payInfo.diy_price }}元</span>
                </div>
            </div>
        </van-popup>
        <!-- 支付结果弹窗 -->
        <pay-popup v-if="showPopup" :popup-visible.sync="showPopup" :type="payStatus" @confrim="payConfrim" />
    </div>
</template>

<script>
import { Cell, CellGroup, Popup, RadioGroup, Radio, Swipe, SwipeItem, Button } from 'vant'
import PayPopup from '@/components/PayPopup.vue'
export default {
    components: {
        [Cell.name]: Cell,
        [CellGroup.name]: CellGroup,
        [RadioGroup.name]: RadioGroup,
        [Radio.name]: Radio,
        [Popup.name]: Popup,
        [Swipe.name]: Swipe,
        [SwipeItem.name]: SwipeItem,
        [Button.name]: Button,
        PayPopup
    },
    data () {
        return {
            title: '',
            bgStyle: '',
            reload: false,
            showPopup: false,
            payStatus: 0, // 支付结果，0=失败，1=成功
            indexCfg: {},
            config: {},
            showPay: false, // 支付方式弹窗
            payInfo: {},
            checked: 'alipay',
            paymentList: [],
            wallet: 0, // 会员账户余额
            pageConfig: '', // 页面配置
            freeOptions: [],
            receiveBusy: false,
            equityList: [
                {
                    name: '一键发圈',
                    icon: 'https://h5.dhcc.wang/assets/newCloudwx/equity_icon_01.png'
                },
                {
                    name: '智能跟发',
                    icon: 'https://h5.dhcc.wang/assets/newCloudwx/equity_icon_02.png'
                },
                {
                    name: '云端自动',
                    icon: 'https://h5.dhcc.wang/assets/newCloudwx/equity_icon_03.png'
                },
                {
                    name: '智能群控',
                    icon: 'https://h5.dhcc.wang/assets/newCloudwx/equity_icon_04.png'
                }
            ]
        }
    },
    created () {
        window.scroll(0, 0)
        this.setHeader()
    },
    mounted () {
        this.init()
    },
    methods: {
        init (loading = true) {
            this.$api.wechatConfig({}, loading).then(res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.config = res.data
                if (res.data.mac_toll_rules && res.data.mac_toll_rules.length > 0) {
                    this.payInfo = res.data.mac_toll_rules[0]
                }
                this.freeOptions = []
                if (res.data.mac_pay_type.length > 0) {
                    let alipay = 0; let wxpay = 0
                    this.paymentList = []
                    if (res.data.mac_rule_level.switch) { // 达到等级
                        this.freeOptions.push({
                            type: 'level',
                            title: `达到${res.data.mac_rule_level.name}等级`,
                            sub_title: `符合条件可免费领取${res.data.mac_rule_level.num}个月时长`,
                            status: res.data.mac_rule_level.status
                        })
                    }
                    if (res.data.mac_rule_perform.switch) { // 满足佣金
                        this.freeOptions.push({
                            type: 'commission',
                            title: `近30天已结算订单≥${res.data.mac_rule_perform.num}笔`,
                            sub_title: `符合条件可免费领取1个月时长`,
                            status: res.data.mac_rule_perform.status
                        })
                    }
                    console.log(res.data.mac_pay_type)
                    res.data.mac_pay_type.forEach(ele => {
                        if (ele == 'alipay') {
                            this.paymentList.push({
                                name: '支付宝支付',
                                icon: 'https://h5.dhcc.wang/images/O2Oplus/pay_alipay.png',
                                type: 'alipay'
                            })
                            alipay = 1
                        }
                        if (ele == 'wxpay') {
                            this.paymentList.push({
                                name: '微信支付',
                                icon: 'https://h5.dhcc.wang/images/O2Oplus/pay_wechat.png',
                                type: 'wxpay'
                            })
                            wxpay = 1
                        }
                        if (ele == 'credit') {
                            this.getWallet()
                            this.paymentList.push({
                                name: '余额支付',
                                icon: 'https://h5.dhcc.wang/images/O2Oplus/pay_balance.png',
                                type: 'credit'
                            })
                        }
                    })
                    this.checked = alipay ? 'alipay' : wxpay ? 'wxpay' : 'credit'
                    console.log(this.checked)
                }
                this.title = res.data.mac_title
                // this.getPageConfig()
            }).finally(() => {
                setTimeout(() => {
                    this.reload = false
                }, 500)
            })
        },
        getWallet () {
            this.$api.getUserIndex({}, false).then(res => {
                if (res.code == 1 && res.data) {
                    this.wallet = res.data.credit
                }
            })
        },
        handleReceive (item) {
            if (item.status == -1) return
            // if (item.status == 0) {
            //     return this.$toast(item.type == 'level' ? '未达到指定等级' : '近30天已结算订单不满足')
            // }
            if (this.receiveBusy) {
                return this.$toast('操作繁忙，请稍后再试！')
            }
            this.receiveBusy = true
            this.$api.deviceBuy({
                pay_type: item.type == 'level' ? 'level' : 'perform'
            }).then(res => {
                this.$toast(res.msg)
                setTimeout(() => {
                    this.init(false)
                    if (res.code == 1) {
                        this.back()
                    }
                }, 1500)
            }).finally(() => {
                this.receiveBusy = false
            })
        },
        select (item) {
            this.payInfo = item
        },
        buy () {
            if (this.config.mac_pay_type.length < 1) {
                return this.$toast('很抱歉，暂未开启支付~')
            }
            let title, day
            switch (this.payInfo.months) {
            case '1':
                title = '月卡'
                day = 30
                break
            case '3':
                title = '季卡'
                day = 90
                break
            case '6':
                title = '半年卡'
                day = 180
                break
            case '12':
                title = '年卡'
                day = 365
                break
            default:
                break
            }
            this.payInfo.title = title
            this.payInfo.day = day
            this.showPay = true
        },
        submit () {
            let params = {
                pay_type: this.checked,
                id: this.payInfo.id
                // day: this.payInfo.day
            }
            if (this.checked == 'credit') {
                if (Number(this.wallet) < Number(this.payInfo.diy_price)) {
                    this.$toast('钱包余额不足，请选择其他支付方式')
                    return
                }
                // 检测是否设置支付密码
                this.$api.getPayPasswordStatus().then(res => {
                    if (res.code != 1) {
                        return this.$toast(res.msg)
                    }
                    if (res.data.status == 1) {
                        this.DS.call('DS.payInputPwd', {
                            payPwdContent: `${this.config.mac_title}${this.payInfo.name}`,
                            payPwdMoney: Number(this.payInfo.diy_price)
                        }, (ret) => {
                            this.$set(params, 'pay_password', ret)
                            this.$api.deviceBuy(params).then(res => {
                                if (res.code != 1) {
                                    return this.$toast(res.msg)
                                }
                                this.showPay = false
                                this.payStatus = 1
                                this.showPopup = true
                            })
                        })
                    } else {
                        this.$toast('请先设置支付密码')
                        setTimeout(() => {
                            this.DS.call('DS.openPage', {
                                page: 'EditPayPwdPage'
                            })
                        }, 800)
                    }
                })
            } else {
                this.$api.deviceBuy(params).then(res => {
                    if (res.code != 1) {
                        return this.$toast(res.msg)
                    }
                    let obj = {
                        payType: this.checked == 'alipay' ? 1 : 2
                    }
                    if (obj.payType == 1) {
                        this.$set(obj, 'aliOrderStr', res.data.pay_data)
                    } else {
                        this.$set(obj, 'orderStr', res.data.pay_data)
                    }
                    this.nativePay(obj)
                })
            }
        },
        nativePay (params) {
            this.DS.call('DS.payInfo', params, (res) => {
                this.payStatus = res
                this.showPay = false
                this.showPopup = true
            })
        },
        refresh () {
            this.reload = true
            this.init()
        },
        payConfrim () {
            this.showPopup = false
            this.init()
            if (this.payStatus == 1) {
                this.back()
            }
        },
        back () {
            this.$router.go(-1)
        },
        setHeader () {
            this.$common.setHeader({
                native_headershow: 0,
                topstyle: 'topcolor',
                native_top_words_color: '#ffffff',
                str_link_color: '#ffffff',
                end_link_color: '#ffffff'
            })
        },
        calcDiscount (now, origin) {
            return parseInt(Number(now) / Number(origin) * 10)
        },
        openPage () {
            this.$router.push('/exchangeRecord')
        }

    }
}
</script>
<style lang="less" scoped>
.cont {
    height: 100%;
    font-size: 14px;
    padding-top: 46px;

    .user-info {
        background: linear-gradient(334deg, #2a211d, #524135);
        border-radius: 14px 14px 0 0;
        padding: 20px 18px 50px;
        margin: 0 10px;
        color: #fee0b8;
        .avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
        }

        .nickname {
            margin-bottom: 4px;
        }
    }

    .custom-img {
        width: 100%;
        margin-top: -35px;
        background: linear-gradient(180deg,#fffdf5,#ffeedb);
        border-radius: 10px;
        border: 1px solid #ffeedc;
        height: 80px;
        color: #674d36;
        img {
            width: 36px;
            border: 1px solid #d3b59b;
            border-radius: 100px;
        }
    }

    .card-title {
        position: relative;
        margin: 15px 0px 10px;
        padding-left: 10px;
        font-size: 16px;
        font-weight: bold;

        &::before {
            content: '';
            position: absolute;
            left: 0;
            height: 70%;
            width: 2px;
            top: 50%;
            transform: translateY(-50%);
            background: #222222;
            border-radius: 1px;
        }
    }

    .receive-free {
        padding: 0px 18px;
        border-radius: 10px;

        .item {
            display: flex;
            align-items: center;
            padding: 20px 0px;
            border-bottom: 1px solid #f5f5f5;

            &:last-of-type {
                border: none;
            }

            .icon {
                width: 26px;
                height: 26px;
            }

            .text {
                flex: 1;
                display: flex;
                flex-direction: column;
                padding: 0px 8px;
                font-weight: bold;

                &-sub {
                    margin-top: 4px;
                    font-size: 11px;
                    color: #999999;
                    font-weight: normal;
                }
            }

            .btn {
                padding: 4px 18px;
                background: linear-gradient(144deg, #F8E8C1 0%, #F2D093 100%);
                color: #7E3D0D;
                border-radius: 50px;

                &.month {
                    padding: 4px 9px;
                }

                &.disabled {
                    background: #f5f5f5;
                    color: #666;
                }
            }
        }
    }

    .notes {
        margin-top: 15px;
        line-height: 20px;

        h3 {
            margin: 0 0 10px;
        }

        p {
            padding: 0;
            margin: 5px 0;
            font-size: 12px;
            color: #777777;
        }
    }

    .payment {
        &-cont {
            /deep/ .van-cell {
                padding-left: 0;
                padding-right: 0;
                line-height: 36px;
            }

            /deep/ .van-cell::after {
                // display: none;
            }

            /deep/ [class*=van-hairline]::after {
                display: none;
            }

            .radio-title {
                .icon {
                    width: 18px;
                    height: 18px;
                    margin-right: 5px;
                }
            }

            .wallet {
                margin-left: 5px;
                color: #ff3b3b;
            }
        }
        &-title {
            border-top: 1px solid #f5f5f5;
            padding-top: 10px;
            text-align: center;
        }
    }

    .btn-group {
        &-item {
            width: 100%;
            text-align: center;
            padding: 10px 0;
        }

        .cancel {
            color: #222;
            background: #f5f5f5;
            border-radius: 5px;
        }

        .confrim {
            border-radius: 100px;
            color: #fee0b8;
            font-size: 16px;
            background: linear-gradient(334deg,#2a211d,#524135);
        }
    }
}

.pay-list {
    border-radius: 10px;
    border: 1px solid #f0f0f0;
    background: #ffffff;
    box-shadow: 0px 3px 3px #f5f5f5;
    margin: 5px;
    .tag {
        border-radius: 9px 0 9px 0;
        background-image: linear-gradient(131deg,#fff,#feeac8 32%,#fad9b1 88%,#ffc99f);
        padding: 2px 0;
        width: 60px;
        text-align: center;
        font-size: 11px;
        color: #672e12;
    }
    .new-tag{
        background-image: linear-gradient(131deg, #f7ca38, #fc4533 32%, #f35141 88%, #ffc99f);
        color: #fff;
    }

    .price-original {
        text-decoration: line-through;
    }
}

.pay-list-active {
    background-image: linear-gradient(319deg,#ffddba,#ffefda);
    border-color: #fee0b8;
    color: #a06142;
}

.buy {
    color: #fee0b8;
    background: linear-gradient(334deg,#2a211d,#524135);
    border-radius: 100px;
    height: 46px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20px 0;
    font-weight: bold;
    font-size: 16px;
}</style>